<template>
  <Box class="" :title="title" :animate="true" style="width: 33%;" v-if="!loading">
    <div style="display: flex; flex-direction: column; gap: 10px;" v-loading="loading"
      v-if="!loading && !isEmpty(data)">
      <div>
        <el-select v-model="month" placeholder="选择月份" style="width: 140px;float: right">
          <template #label="{ label, value }">
            <span style="font-weight: bold">月份: </span>
            <span>{{ value }}</span>
          </template>
          <el-option v-for=" item in Object.keys(data[card])" :key="item" :label="item" :value="item" />
        </el-select>
        <el-select v-model="card" placeholder="选择卡号" style="width: 200px;float: right;margin-right: 20px;">
          <template #label="{ label, value }">
            <span style="font-weight: bold">银行卡: </span>
            <span>{{ value }}</span>
          </template>
          <el-option v-for=" item in Object.keys(data)" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
      <div style="display: flex; gap: 10px;">
        <el-progress type="dashboard" :percentage="scoreKey ? Math.floor(data[card][month].props[scoreKey] * 100) : 0"
          :width="80">
          <template #default="{ percentage }">
            <span class="percentage-value">{{ percentage }}</span>
            <span class="percentage-label">风险值</span>
          </template>
        </el-progress>
        <InfoItem style="flex: 1" :title="store.schemas[scenario][h].split('$')[0]"
          :value="data[card][month]['props'][h]" v-for="h in highlights" :key="h">
        </InfoItem>
      </div>
      <div style="height: 140px;">
        <el-scrollbar height="100%" v-if="month != null && card != null">
          <el-descriptions :column="1" border style="background: none; overflow: hidden;">
            <template v-for="[k, v] in (Object.entries(data[card][month].props || {}))" v-bind:key="k">
              <el-descriptions-item v-if="store.schemas[scenario][k].split('$')[2] != 'archive'"
                :label="store.schemas[scenario][k].split('$')[0] + '：'" label-align="right" label-class-name="label">
                <el-tag type="success"><el-text truncated style="max-width: 160px;">{{ v === null ? '不涉及' : v
                    }}</el-text></el-tag>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-scrollbar>
      </div>

      <Line style="height: 100px;"
        :data="sortBy(Object.keys(data).flatMap(c => Object.keys(data[c]).sort().map(m => ({ '月份': m, '风险值': Math.floor(data[c][m].props[scoreKey] * 100), s: c })), '月份'))">
      </Line>
    </div>
    <div v-else>
      <el-empty description="当前用户不涉及该场景" />
    </div>
  </Box>
</template>

<script lang="ts" setup>
import { computed, watch } from 'vue'
import Box from '../components/Box.vue'
import Box1 from '@/components/Box1.vue'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import InfoItem from './InfoItem.vue'
import { usePortraitStore } from '@/stores/portrait'
import { nebulaExec } from '@/utils/request'
import { groupBy, isEmpty, sortBy } from 'lodash'
import { useScoreStore } from '@/stores/score'
import { useMetaStore } from '@/stores/meta'
import { useSchemaStore } from '@/stores/schema'
import Line from './Line.vue'


const store = usePortraitStore()
const scoreStore = useScoreStore()
const metaStore = useMetaStore()
const schemaStore = useSchemaStore()

const props = defineProps(['title', 'highlights', 'scoreKey', 'scenario', 'id', 'labels'])
const loading = ref(true)
const data = ref({})
const card = ref(null)
const month = ref(null)

async function fetchData() {
  try {
    const resp = await nebulaExec(`MATCH (u)-[]->(c)-[e:${props.scenario}]->(c) WHERE id(u) == "${props.id}" return e`)
    // const resp = await nebulaExec(`FETCH PROP ON ${props.scenario} "${props.card}" -> "${props.card}"@${props.month} YIELD properties(edge)`)
    if (!isEmpty(resp)) {
      const result = groupBy(resp.e, 'src');
      Object.keys(result).forEach(key => {
        const subGroup = groupBy(result[key], 'rank');
        Object.keys(subGroup).forEach(sk => {
          subGroup[sk] = subGroup[sk][0]
        })
        result[key] = subGroup;
      });
      data.value = result
      card.value = resp.e[0].src
      month.value = resp.e[0].rank
      scoreStore.userScores[props.title] = resp.e.map(e => e.props[props.scoreKey])
    } else {
      scoreStore.userScores[props.title] = []
      metaStore.userLabels[props.title] = []
    }
  } finally {
    loading.value = false
  }
}

fetchData()
watch(card, () => { month.value = Object.keys(data.value[card.value])[0] })
watch([month, card], () => {
  if (props.labels && card.value && month.value) {
    metaStore.userLabels[props.scenario] = Object.entries(data.value[card.value][month.value].props)
      .filter(([k, v]) => props.labels.includes(k) && v > 0)
      .map(([k, v]) => schemaStore.schemas[props.scenario][k].split('$')[0])
  }
})

// watch(
//   [() => props.id, () => props.month],
//   async (newVals, oldVals) => {
//     loading.value = true;
//     await fetchData();
//   }
// );

</script>

<style lang="css" scoped>
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 28px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 12px;
}
</style>
